﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Collections.ObjectModel;
using GranitePackageSystem.Views.ChildWindows;
using GranitePackageSystem.GranitePackagingService;

namespace GranitePackageSystem.Views.Licensing
{
    public partial class LicensingApprovalView : Page
    {
        private ObservableCollection<ApplicationInformation> SoftwareUsers;
        private ObservableCollection<ApplicationInformation> PreviousVersionSoftwareUsers;
        private ObservableCollection<ApplicationInformation> RemovedUsersCurrVersion;
        private ObservableCollection<WorkLogEntry> workLog;
        private ObservableCollection<String> destinationOUList = new ObservableCollection<string>() { "Gatekept or TrueUp", "Non-Unique License", "Quarantine", "Track Only", "Unique License" };
        private GranitePackagingService.Request currentRequest;
        private GranitePackagingService.Package packageData;
        private GranitePackagingService.Program programData;
        private GranitePackagingService.LicensingData licData;

        private bool newLicensingData = true;
        private bool softwareContracted = true;
        private bool inputsLock = false;


        private int _errorCount = 0;

        public LicensingApprovalView()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            checkRoles();
            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();

            if (App.Current.Resources.Contains("Current Request"))
            {
                currentRequest = App.Current.Resources["Current Request"] as GranitePackagingService.Request;

                boxADGroupDestinationOU.ItemsSource = destinationOUList;
                boxADGroupDestinationOU.SelectedIndex = 1;
                
                busyIndicatorMain.IsBusy = true;
                busyIndicatorMain.BusyContent = "Loading Request Licensing Data";

                proxy.getPackageListCompleted += new EventHandler<getPackageListCompletedEventArgs>(proxy_getPackageListCompleted_INIT);
                proxy.getPackageListAsync(currentRequest);
            }
            else
            {
                this.NavigationService.Navigate(new System.Uri("/Home", System.UriKind.Relative));
            }
        }

        private void checkRoles()
        {
            Web.User user = WebContext.Current.User;
            bool userInARole = false;

            if (user.IsInRole("GENMILLS\\GPS_Administrators")) { userInARole = true; }
            if (user.IsInRole("GENMILLS\\GPS_LicensingApprovers")) { userInARole = true; }

            if (userInARole) { }
            else { this.NavigationService.Navigate(new System.Uri("/Unauthorized", System.UriKind.Relative)); }
        }
        void proxy_getPackageListCompleted_INIT(object sender, getPackageListCompletedEventArgs e)
        {

            //Valid amount of Packages Per Request
            if (e.Result.Count == 1)
            {
                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.InnerChannel.OperationTimeout = TimeSpan.FromMinutes(60);
                packageData = e.Result[0];
                proxy.getProgramListCompleted += new EventHandler<getProgramListCompletedEventArgs>(proxy_getProgramListCompleted_INIT);
                proxy.getProgramListAsync(packageData);
                panelPackageInfoDetails.DataContext = packageData;

                busyIndicatorUsersGrid.IsBusy = true;
                busyIndicatorUsersGrid.BusyContent = "Loading User Information";

                proxy.getApplicationInstallBaseInformationCompleted += new EventHandler<getApplicationInstallBaseInformationCompletedEventArgs>(proxy_getApplicationInstallBaseInformationCompleted);
                proxy.getApplicationInstallBaseInformationAsync(packageData.Name, packageData.Version);
            }
            else
            {
                MessageBox.Show("Invalid Number of packages for this request");
                this.NavigationService.Navigate(new Uri("/Home", System.UriKind.Relative));
            }
        }
        void proxy_getProgramListCompleted_INIT(object sender, getProgramListCompletedEventArgs e)
        {
            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            //Valid number of Programs
            if (e.Result.Count == 1)
            {
                programData = e.Result[0];

                proxy.getLicensingDataCompleted += new EventHandler<getLicensingDataCompletedEventArgs>(proxy_getLicensingDataCompleted_INIT);
                proxy.getLicensingDataAsync(currentRequest);
            }
            else
            {
                MessageBox.Show("Invalid Number of programs for this request");
                this.NavigationService.Navigate(new Uri("/Home", System.UriKind.Relative));
            }
        }
        void proxy_getLicensingDataCompleted_INIT(object sender, getLicensingDataCompletedEventArgs e)
        {
            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            licData = e.Result;

            switch (currentRequest.IncomingSource)
            {
                case "Windows 7 Upgrade Project":
                    boxRequestSource.SelectedIndex = 0;
                    break;
                case "New Software":
                    boxRequestSource.SelectedIndex = 1;
                    break;
                default:
                    boxRequestSource.SelectedIndex = 0;
                    break;
            }

            proxy.getAllDivisionsCompleted += new EventHandler<getAllDivisionsCompletedEventArgs>(proxy_getAllDivisionsCompleted_INIT);
            proxy.getAllDivisionsAsync();
        }
        void proxy_getAllDivisionsCompleted_INIT(object sender, getAllDivisionsCompletedEventArgs e)
        {
            boxDivisonOfOwnership.ItemsSource = e.Result;
            if (e.Result.Count > 0)
            {
                boxDivisonOfOwnership.SelectedIndex = 0;
            }

            // If No existing Licensing Data
            if (licData.LicensingID == null)
            {
                this.NavigationService.Navigate(new System.Uri("/Request/Licensing", System.UriKind.Relative));
            }
            // Existing Licensing Data for Request
            else
            {
                updateLicensingInputs(licData);

                if (currentRequest.Status.Equals("Pending Approval") || currentRequest.Status.Equals("Pending"))
                {
                    lockInputs();
                    string adGroupName;

                    Models.ADGroup group = new Models.ADGroup();

                    boxADGroupName.DataContext = group;
                    boxADGroupNotes.DataContext = group;
                    boxADGroupDescription.DataContext = group;
                    boxADGroupOwner.DataContext = group;
                    
                    if (!currentRequest.ADGroupDescription.Equals(String.Empty))
                    {
                        boxADGroupDescription.Text = currentRequest.ADGroupDescription;   
                    }
                    if (!currentRequest.DestinationOU.Equals(String.Empty))
                    {
                        boxADGroupDestinationOU.SelectedItem = currentRequest.DestinationOU;
                    }
                    if (!currentRequest.ADGroupName.Equals(String.Empty))
                    {
                        adGroupName = currentRequest.ADGroupName;
                        boxADGroupName.Text = currentRequest.ADGroupName;
                    }
                    else
                    {
                        adGroupName = "GMI_APP_" + packageData.Name + "_" + packageData.Version + "_SI";
                        adGroupName = adGroupName.Replace(' ', '_');
                        adGroupName = adGroupName.Replace(",", string.Empty);
                        adGroupName = adGroupName.Replace("{", string.Empty);
                        adGroupName = adGroupName.Replace("(", string.Empty);
                        adGroupName = adGroupName.Replace("}", string.Empty);
                        adGroupName = adGroupName.Replace(")", string.Empty);
                        boxADGroupName.Text = adGroupName;
                    }
                    if (!currentRequest.ADGroupNotes.Equals(String.Empty))
                    {
                        boxADGroupNotes.Text = currentRequest.ADGroupNotes;
                    }
                    if (currentRequest.LicensingOwner.Equals(String.Empty))
                    {
                        boxADGroupOwner.Text = WebContext.Current.User.Name.Split('\\')[1];
                    }
                    else
                    {
                        boxADGroupOwner.Text = currentRequest.LicensingOwner;
                    }
                    busyIndicatorMain.BusyContent = "Getting Request Work Log Data";

                    GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                    proxy.getRequestWorkLogCompleted += new EventHandler<getRequestWorkLogCompletedEventArgs>(proxy_getRequestWorkLogCompleted_INIT);
                    proxy.getRequestWorkLogAsync(currentRequest);

                    spinnerGroupName.Visibility = System.Windows.Visibility.Visible;
                    boxADGroupNameNeworExisting.Visibility = System.Windows.Visibility.Collapsed;
                    proxy.getGroupFriendlyNameCompleted += new EventHandler<getGroupFriendlyNameCompletedEventArgs>(proxy_getGroupFriendlyNameCompleted_INIT);
                    proxy.getGroupFriendlyNameAsync(adGroupName, "genmills.com");

                    spinnerGroupOwner.Visibility = System.Windows.Visibility.Visible;
                    boxADGroupOwnerValid.Visibility = System.Windows.Visibility.Collapsed;
                    proxy.getUserFriendlyNameCompleted += new EventHandler<getUserFriendlyNameCompletedEventArgs>(proxy_getUserFriendlyNameCompleted_INIT);
                    proxy.getUserFriendlyNameAsync(boxADGroupOwner.Text, "genmills.com");
                }
                else
                {
                    GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                    proxy.getRequestCompleted += new EventHandler<getRequestCompletedEventArgs>(proxy_getRequestCompleted);
                    proxy.getRequestAsync(currentRequest.requestID, 0);
                }
            }
        }

        void proxy_getUserFriendlyNameCompleted_INIT(object sender, getUserFriendlyNameCompletedEventArgs e)
        {
            spinnerGroupOwner.Visibility = System.Windows.Visibility.Collapsed;
            if (!(e.Result.Equals(String.Empty)))
            {
                SolidColorBrush greenBrush = new SolidColorBrush();
                greenBrush.Color = Colors.Green;

                boxADGroupOwnerValid.Text = "Valid User";
                boxADGroupOwnerValid.Foreground = greenBrush;
                boxADGroupOwnerValid.Visibility = System.Windows.Visibility.Visible;

                boxADGroupOwner.Text = e.Result;
            }
            else
            {
                SolidColorBrush redBrush = new SolidColorBrush();
                redBrush.Color = Colors.Red;

                boxADGroupOwnerValid.Text = "Invalid User";
                boxADGroupOwnerValid.Foreground = redBrush;
                boxADGroupOwnerValid.Visibility = System.Windows.Visibility.Visible;
            }
        }

        void proxy_getGroupFriendlyNameCompleted_INIT(object sender, getGroupFriendlyNameCompletedEventArgs e)
        {
            spinnerGroupName.Visibility = System.Windows.Visibility.Collapsed;
            if (!(e.Result.Equals(String.Empty)))
            {
                SolidColorBrush greenBrush = new SolidColorBrush();
                greenBrush.Color = Colors.Green;

                boxADGroupNameNeworExisting.Text = "Existing Group";
                boxADGroupNameNeworExisting.Foreground = greenBrush;
                boxADGroupNameNeworExisting.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                SolidColorBrush blueBrush = new SolidColorBrush();
                blueBrush.Color = Colors.Blue;

                boxADGroupNameNeworExisting.Text = "New Group";
                boxADGroupNameNeworExisting.Foreground = blueBrush;
                boxADGroupNameNeworExisting.Visibility = System.Windows.Visibility.Visible;
            }
        }

        void proxy_getRequestWorkLogCompleted_INIT(object sender, getRequestWorkLogCompletedEventArgs e)
        {
            busyIndicatorMain.IsBusy = false;
            workLog = new ObservableCollection<WorkLogEntry>();
            if (e.Result.Count > 0)
            {
                foreach (WorkLogEntry entry in e.Result)
                {
                    WorkLogEntry modifiedEntry = entry;
                    modifiedEntry.NoteDate = modifiedEntry.NoteDate.ToLocalTime();

                    workLog.Add(modifiedEntry);
                }
            }
            gridWorkLog.ItemsSource = workLog;
        }

        private void lockInputs()
        {
            boxDepartmentOfOwnership.IsEnabled = false;
            boxDivisonOfOwnership.IsEnabled = false;
            boxLicenseKeyChoice.IsEnabled = false;
            boxPONumber.IsEnabled = false;
            boxSoftwareCost.IsEnabled = false;
            boxSoftwareEULA.IsEnabled = false;
            boxSoftwareOrigin.IsEnabled = false;
            boxSoftwareProcurementMethod.IsEnabled = false;
            listBoxLicenseKeys.IsEnabled = false;
            btnAddLicenseKey.IsEnabled = false;
            btnRemoveLicenseKey.IsEnabled = false;
            inputsLock = true;
            btnSaveLicensingData.IsEnabled = false;
            boxRequestSource.IsEnabled = false;
        }
        private void unlockInputes()
        {
            boxDepartmentOfOwnership.IsEnabled = true;
            boxDivisonOfOwnership.IsEnabled = true;
            boxLicenseKeyChoice.IsEnabled = true;
            boxPONumber.IsEnabled = true;
            boxSoftwareCost.IsEnabled = true;
            boxSoftwareEULA.IsEnabled = true;
            boxSoftwareOrigin.IsEnabled = true;
            boxSoftwareProcurementMethod.IsEnabled = true;
            listBoxLicenseKeys.IsEnabled = true;
            btnAddLicenseKey.IsEnabled = true;
            btnRemoveLicenseKey.IsEnabled = true;
            inputsLock = false;
            btnSaveLicensingData.IsEnabled = true;
            boxRequestSource.IsEnabled = true;
        }

        private void unlockLicensingInputs()
        {
            boxDepartmentOfOwnership.IsEnabled = true;
            boxDivisonOfOwnership.IsEnabled = true;
            boxLicenseKeyChoice.IsEnabled = true;
            boxPONumber.IsReadOnly = false;
            boxSoftwareCost.IsEnabled = true;
            boxSoftwareEULA.IsReadOnly = false;
            boxSoftwareOrigin.IsEnabled = true;
            boxSoftwareProcurementMethod.IsEnabled = true;
            listBoxLicenseKeys.IsEnabled = true;
            inputsLock = false;
            btnSaveLicensingData.IsEnabled = true;
            boxRequestSource.IsEnabled = true;
        }
        private void updateLicensingInputs(LicensingData licData)
        {
            foreach (ComboBoxItem item in boxSoftwareOrigin.Items)
            {
                if (item.Content.Equals(licData.SoftwareOrigin))
                {
                    boxSoftwareOrigin.SelectedItem = item;
                    break;
                }
            }
            switch (licData.SoftwareOrigin)
            {
                case "Not General Mills Developed":
                    switch (licData.ProcurementMethod.ToUpper())
                    {
                        case "SAP SRM REQUEST":
                            boxSoftwareProcurementMethod.SelectedIndex = 0;
                            boxPONumber.Text = licData.PO_Number;
                            break;
                        case "MAXIMO REQUEST":
                            boxSoftwareProcurementMethod.SelectedIndex = 1;
                            boxPONumber.Text = licData.PO_Number;
                            break;
                        case "IS Sourcing PCard":
                            boxSoftwareProcurementMethod.SelectedIndex = 2;
                            break;
                        case "CORPORATE CREDIT CARD":
                            boxSoftwareProcurementMethod.SelectedIndex = 3;
                            break;
                        case "PERSONAL CREDIT CARD":
                            boxSoftwareProcurementMethod.SelectedIndex = 4;
                            break;
                        case "NO COST":
                            boxSoftwareProcurementMethod.SelectedIndex = 5;
                            panelSoftwareCost.Visibility = System.Windows.Visibility.Collapsed;
                            panelPONumber.Visibility = System.Windows.Visibility.Collapsed;
                            break;


                        default:
                            break;
                    }

                    switch (licData.SoftwareCost)
                    {
                        case "0-$1,000":
                            boxSoftwareCost.SelectedIndex = 0;
                            break;
                        case "1,000-$10,000":
                            boxSoftwareCost.SelectedIndex = 1;
                            break;
                        case "$10,000+":
                            boxSoftwareCost.SelectedIndex = 2;
                            break;
                        default:
                            break;
                    }

                    softwareContracted = licData.SoftwareContracted;
                    updateSoftwareContracted(softwareContracted);

                    if (!licData.SoftwareContracted)
                    {
                        boxSoftwareEULA.SelectAll();
                        boxSoftwareEULA.Selection.Text = licData.SoftwareEULA;
                    }
                    if (licData.LicenseKeys.Count != 0)
                    {
                        if (licData.LicenseKeys.Count > 1)
                        {
                            boxLicenseKeyChoice.SelectedIndex = 1;
                        }
                        else
                        {
                            boxLicenseKeyChoice.SelectedIndex = 0;
                        }
                        foreach (LicenseKey licKey in licData.LicenseKeys)
                        {
                            listBoxLicenseKeys.Items.Add(licKey.Key.ToString());
                        }
                    }
                    else
                    {
                        boxLicenseKeyChoice.SelectedIndex = 2;
                    }
                    break;
                case "General Mills Developed":
                    panelSubSoftwareOrigin.Visibility = System.Windows.Visibility.Collapsed;
                    break;
            }

            foreach (Division division in boxDivisonOfOwnership.Items)
            {
                if (division.Name.Equals(licData.DivisionOfOwnership))
                {
                    boxDivisonOfOwnership.SelectedIndex = boxDivisonOfOwnership.Items.IndexOf(division);
                    break;
                }
            }
            if (!licData.DepartmentOfOwnership.Equals(string.Empty))
            {
                foreach (Department department in boxDepartmentOfOwnership.Items)
                {
                    if (department.name.Equals(licData.DepartmentOfOwnership))
                    {
                        boxDepartmentOfOwnership.SelectedIndex = boxDepartmentOfOwnership.Items.IndexOf(department);
                        break;
                    }
                }
            }
            else { panelDepartmentOfOwnership.Visibility = System.Windows.Visibility.Collapsed; }
        }
        private void updateSoftwareContracted(bool status)
        {
            softwareContracted = status;
            if (status == true)
            {
                btnSoftwareContracted_YES.Background = new SolidColorBrush(new Color() { A = 255, B = 242, G = 188, R = 149 });
                btnSoftwareContracted_NO.Background = new SolidColorBrush();
                panelSoftwareEULA.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                btnSoftwareContracted_YES.Background = new SolidColorBrush();
                btnSoftwareContracted_NO.Background = new SolidColorBrush(new Color() { A = 255, B = 242, G = 188, R = 149 });
                panelSoftwareEULA.Visibility = System.Windows.Visibility.Visible;
            }
        }
        void proxy_getApplicationInstallBaseInformationCompleted(object sender, getApplicationInstallBaseInformationCompletedEventArgs e)
        {
            ObservableCollection<ApplicationInformation> dataSet = e.Result;

            ObservableCollection<String> users = new ObservableCollection<String>();
            ObservableCollection<String> pVersionUsers = new ObservableCollection<String>();

            SoftwareUsers = new ObservableCollection<ApplicationInformation>();
            PreviousVersionSoftwareUsers = new ObservableCollection<ApplicationInformation>();
            RemovedUsersCurrVersion = new ObservableCollection<ApplicationInformation>();

            foreach (ApplicationInformation appInfo in dataSet)
            {
                if (appInfo.version.Equals(packageData.Version))
                {
                    if (!users.Contains(appInfo.userName))
                    {
                        users.Add(appInfo.userName);
                        SoftwareUsers.Add(appInfo);
                    }
                }
                else
                {
                    if (!(pVersionUsers.Contains(appInfo.userName + " " + appInfo.version) || appInfo.friendlyUserName.Equals(String.Empty)))
                    {
                        pVersionUsers.Add(appInfo.userName + " " + appInfo.version);
                        PreviousVersionSoftwareUsers.Add(appInfo);
                    }
                }
            }

            dataGridSoftwareUsers.ItemsSource = SoftwareUsers;
            dataGridSoftwarePreviousUsers.ItemsSource = PreviousVersionSoftwareUsers;
            dataGridSoftwareRemovedUsers.ItemsSource = RemovedUsersCurrVersion;

            busyIndicatorUsersGrid.IsBusy = false;
        }
        private void btnCurrVersionRemoveSelected_Click(object sender, RoutedEventArgs e)
        {
            ApplicationInformation[] tCol = new ApplicationInformation[SoftwareUsers.Count];
            SoftwareUsers.CopyTo(tCol, 0);
            foreach (ApplicationInformation appInfo in tCol)
            {
                if (appInfo.include)
                {
                    SoftwareUsers.Remove(appInfo);
                    appInfo.include = false;
                    if (appInfo.version.Equals(packageData.Version))
                    {
                        RemovedUsersCurrVersion.Add(appInfo);
                    }
                    else
                    {
                        PreviousVersionSoftwareUsers.Add(appInfo);
                    }
                }
            }

            if (RemovedUsersCurrVersion.Count > 0)
            {
                panelRemovedUserGrid.Visibility = System.Windows.Visibility.Visible;
            }
        }
        private void btnCurrVersionReAddSelected_Click(object sender, RoutedEventArgs e)
        {
            ApplicationInformation[] tCol = new ApplicationInformation[RemovedUsersCurrVersion.Count];
            RemovedUsersCurrVersion.CopyTo(tCol, 0);
            foreach (ApplicationInformation appInfo in tCol)
            {
                if (appInfo.include)
                {
                    RemovedUsersCurrVersion.Remove(appInfo);
                    appInfo.include = false;
                    SoftwareUsers.Add(appInfo);
                }
            }

            if (RemovedUsersCurrVersion.Count > 0)
            {
                panelRemovedUserGrid.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                panelRemovedUserGrid.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
        private void btnPreviousVersionAddSelected_Click(object sender, RoutedEventArgs e)
        {
            ApplicationInformation[] tCol = new ApplicationInformation[PreviousVersionSoftwareUsers.Count];
            PreviousVersionSoftwareUsers.CopyTo(tCol, 0);
            foreach (ApplicationInformation appInfo in tCol)
            {
                if (appInfo.include)
                {
                    PreviousVersionSoftwareUsers.Remove(appInfo);
                    appInfo.include = false;
                    SoftwareUsers.Add(appInfo);
                }
            }
        }
        private void btnSoftwareContracted_YES_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!inputsLock) { updateSoftwareContracted(true); }
        }
        private void btnSoftwareContracted_NO_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!inputsLock) { updateSoftwareContracted(false); }
        }
        private void boxSoftwareOrigin_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (boxSoftwareOrigin.SelectedIndex == 1)
                {
                    panelSubSoftwareOrigin.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    panelSubSoftwareOrigin.Visibility = System.Windows.Visibility.Visible;
                }
            }
            catch { }
        }
        private void boxLicenseKeyChoice_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (boxLicenseKeyChoice.SelectedIndex == 2)
                {
                    panelLicenseKeyUploader.Visibility = System.Windows.Visibility.Collapsed;
                    listBoxLicenseKeys.Items.Clear();
                    licData.LicenseKeys.Clear();
                }
                else
                {
                    panelLicenseKeyUploader.Visibility = System.Windows.Visibility.Visible;
                }
            }
            catch { }
        }
        private void boxSoftwareProcurementMethod_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                switch (boxSoftwareProcurementMethod.SelectedIndex)
                {
                    case 0:
                        panelPONumber.Visibility = System.Windows.Visibility.Visible;
                        panelSoftwareCost.Visibility = System.Windows.Visibility.Visible;
                        break;
                    case 1:
                        panelPONumber.Visibility = System.Windows.Visibility.Visible;
                        panelSoftwareCost.Visibility = System.Windows.Visibility.Visible;
                        break;
                    case 2:
                        panelPONumber.Visibility = System.Windows.Visibility.Collapsed;
                        panelSoftwareCost.Visibility = System.Windows.Visibility.Visible;
                        break;
                    case 3:
                        panelPONumber.Visibility = System.Windows.Visibility.Collapsed;
                        panelSoftwareCost.Visibility = System.Windows.Visibility.Visible;
                        break;
                    case 4:
                        panelPONumber.Visibility = System.Windows.Visibility.Collapsed;
                        panelSoftwareCost.Visibility = System.Windows.Visibility.Collapsed;
                        break;
                    default:
                        panelPONumber.Visibility = System.Windows.Visibility.Collapsed;
                        panelSoftwareCost.Visibility = System.Windows.Visibility.Visible;
                        break;
                }
            }
            catch { }
        }
        private void boxDivisonOfOwnership_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (((Division)boxDivisonOfOwnership.SelectedItem).Departments.Count > 0)
                {
                    panelDepartmentOfOwnership.Visibility = System.Windows.Visibility.Visible;
                    boxDepartmentOfOwnership.SelectedIndex = 0;
                }
                else
                {
                    panelDepartmentOfOwnership.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
            catch { }
        }
        private void btnAddLicenseKey_Click(object sender, RoutedEventArgs e)
        {
            LicenseKeyEntry licKeyEntryWindow = new LicenseKeyEntry();
            licKeyEntryWindow.Closed += new EventHandler(licKeyEntryWindow_Closed);
            licKeyEntryWindow.Show();
        }

        void licKeyEntryWindow_Closed(object sender, EventArgs e)
        {
            if (((LicenseKeyEntry)sender).DialogResult == true)
            {
                listBoxLicenseKeys.Items.Add(((LicenseKeyEntry)sender).boxLicenseKey.Text);
            }
        }

        private void btnRemoveLicenseKey_Click(object sender, RoutedEventArgs e)
        {
            if (listBoxLicenseKeys.SelectedItem != null)
            {
                listBoxLicenseKeys.Items.Remove(listBoxLicenseKeys.SelectedItem);
            }
        }

        private void btnApproveRequest_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Data.BindingExpression exp = boxADGroupName.GetBindingExpression(TextBox.TextProperty);
            if (exp != null)
            {
                exp.UpdateSource();
            }

            exp = boxADGroupDescription.GetBindingExpression(TextBox.TextProperty);
            if (exp != null)
            {
                exp.UpdateSource();
            }

            exp = boxADGroupNotes.GetBindingExpression(TextBox.TextProperty);
            if (exp != null)
            {
                exp.UpdateSource();
            }

            exp = boxADGroupOwner.GetBindingExpression(TextBox.TextProperty);
            if (exp != null)
            {
                exp.UpdateSource();
            }

            if (_errorCount == 0)
            {
                busyIndicatorMain.IsBusy = true;
                busyIndicatorMain.BusyContent = "Validating Group Owner";
                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.getUserFriendlyNameCompleted += new EventHandler<getUserFriendlyNameCompletedEventArgs>(proxy_getUserFriendlyNameCompleted_ApproveCheck);
                proxy.getUserFriendlyNameAsync(boxADGroupOwner.Text, "genmills");


            }
            else
            {
                MessageBox.Show("Must have a valid AD Group Information");
            }
        }
        void proxy_getUserFriendlyNameCompleted_ApproveCheck(object sender, getUserFriendlyNameCompletedEventArgs e)
        {
            busyIndicatorMain.IsBusy = false;
            if (e.Result.ToString().Equals(String.Empty))
            {
                MessageBox.Show("Invalid User");
            }
            else
            {
                ObservableCollection<RequestMember> reqMemberList = new ObservableCollection<RequestMember>();

                foreach (ApplicationInformation softwareUser in SoftwareUsers)
                {
                    reqMemberList.Add(new RequestMember()
                    {
                        ADSite = softwareUser.ADSite,
                        userFriendlyName = softwareUser.friendlyUserName,
                        userID = softwareUser.userName,
                        comptuerName = softwareUser.installationComputer
                    });
                }

                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.addRequestUsersCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(proxy_addRequestUsersCompleted);
                proxy.addRequestUsersAsync(currentRequest, reqMemberList);

                busyIndicatorMain.IsBusy = true;
                busyIndicatorMain.BusyContent = "Saving initial Membership list";
            }
        }

        void proxy_addRequestUsersCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            App.Current.Resources.Remove("Current Request");
            App.Current.Resources.Add("Current Request", currentRequest);

            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.getRequestCompleted += new EventHandler<getRequestCompletedEventArgs>(proxy_getRequestCompleted_SubmitRequest);
            proxy.getRequestAsync(currentRequest.requestID, 0);
        }

        void proxy_getRequestCompleted_SubmitRequest(object sender, getRequestCompletedEventArgs e)
        {
            currentRequest = e.Result;


            if ((currentRequest.Status.Equals("Pending Approval") || currentRequest.Status.Equals("Pending")) && currentRequest.Stage.Equals("Licensing"))
            {
                Web.User user = WebContext.Current.User;
                currentRequest.Status = "Approved";
                currentRequest.ADGroupName = boxADGroupName.Text;
                currentRequest.ADGroupNotes = boxADGroupNotes.Text;
                currentRequest.ADGroupDescription = boxADGroupDescription.Text;
                currentRequest.LicensingOwner = boxADGroupOwner.Text;
                currentRequest.DestinationOU = boxADGroupDestinationOU.SelectedItem.ToString();

                App.Current.Resources.Remove("Current Request");
                App.Current.Resources.Add("Current Request", currentRequest);

                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.saveRequestCompleted += new EventHandler<saveRequestCompletedEventArgs>(proxy_saveRequestCompleted_Approved);
                proxy.saveRequestAsync(currentRequest);
                busyIndicatorMain.BusyContent = "Approving Request";
            }
            else
            {
                App.Current.Resources.Remove("Current Request");
                App.Current.Resources.Add("Current Request", currentRequest);

                busyIndicatorMain.BusyContent = "Request Approved";
                busyIndicatorMain.IsBusy = false;
            }
        }

        void proxy_saveRequestCompleted_Approved(object sender, saveRequestCompletedEventArgs e)
        {
            if (!e.Result.Stage.Equals("Licensing"))
            {
                busyIndicatorMain.IsBusy = false;
                btnApproveRequest.Visibility = System.Windows.Visibility.Collapsed;
                btnRejectRequest.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.getRequestCompleted += new EventHandler<getRequestCompletedEventArgs>(proxy_getRequestCompleted);
                proxy.getRequestAsync(currentRequest.requestID, 5);
            }
        }

        void proxy_getRequestCompleted(object sender, getRequestCompletedEventArgs e)
        {
            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy = new GranitePackagingServiceSoapClient();

            currentRequest = e.Result;

            Application.Current.Resources.Remove("Current Request");
            Application.Current.Resources.Add("Current Request", e.Result);

            if (currentRequest.Stage.Equals("Licensing"))
            {
                busyIndicatorMain.BusyContent = currentRequest.Status;
                proxy.getRequestCompleted += new EventHandler<getRequestCompletedEventArgs>(proxy_getRequestCompleted);
                proxy.getRequestAsync(currentRequest.requestID, 5);
            }
            else
            {
                busyIndicatorMain.IsBusy = false;
                btnApproveRequest.Visibility = System.Windows.Visibility.Collapsed;
                btnRejectRequest.Visibility = System.Windows.Visibility.Collapsed;
                this.NavigationService.Navigate(new Uri("/Home", UriKind.Relative));
            }

        }

        private void btnEditLicensingData_Click(object sender, RoutedEventArgs e)
        {
            panelLicenseEdit.Visibility = System.Windows.Visibility.Collapsed;
            unlockInputes();
        }
        private bool validateInputFields()
        {
            licData.SoftwareOrigin = boxSoftwareOrigin.SelectionBoxItem.ToString();
            licData.RequestID = currentRequest.requestID;
            switch (licData.SoftwareOrigin)
            {
                case "Not General Mills Developed":
                    licData.ProcurementMethod = boxSoftwareProcurementMethod.SelectionBoxItem.ToString();

                    switch (licData.ProcurementMethod)
                    {
                        case "SAP SRM Request":
                            licData.SoftwareCost = boxSoftwareCost.SelectionBoxItem.ToString();
                            if (boxPONumber.Text.Equals(string.Empty))
                            {
                                MessageBox.Show("Must Enter a PO Number");
                                return false;
                            }
                            else
                            {
                                licData.PO_Number = boxPONumber.Text;
                            }
                            break;
                        case "Maximo Request":
                            licData.SoftwareCost = boxSoftwareCost.SelectionBoxItem.ToString();
                            if (boxPONumber.Text.Equals(string.Empty))
                            {
                                MessageBox.Show("Must Enter a PO Number");
                                return false;
                            }
                            else
                            {
                                licData.PO_Number = boxPONumber.Text;
                            }
                            break;
                        case "Corporate Credit Card":
                            licData.SoftwareCost = boxSoftwareCost.SelectionBoxItem.ToString();
                            break;
                        case "Personal Credit Card":
                            licData.SoftwareCost = boxSoftwareCost.SelectionBoxItem.ToString();
                            break;
                        case "No Cost":
                            break;
                        default:
                            MessageBox.Show("Invalid Procurement Method");
                            return false;
                    }

                    licData.SoftwareContracted = softwareContracted;

                    if (!licData.SoftwareContracted)
                    {
                        boxSoftwareEULA.SelectAll();

                        if (boxSoftwareEULA.Selection.Text.ToString().Equals(string.Empty))
                        {
                            MessageBox.Show("For non contracted software you must enter the EULA");
                            return false;
                        }
                        else
                        {
                            licData.SoftwareEULA = boxSoftwareEULA.Selection.Text.ToString();
                        }
                    }

                    if (boxLicenseKeyChoice.SelectedIndex != 2)
                    {
                        if (listBoxLicenseKeys.Items.Count > 0)
                        {
                            licData.LicenseKeys = new System.Collections.ObjectModel.ObservableCollection<LicenseKey>();
                            foreach (String licKey in listBoxLicenseKeys.Items)
                            {
                                licData.LicenseKeys.Add(new LicenseKey() { Key = licKey, LicenseID = licData.LicensingID, LicenseKeyID = System.Guid.NewGuid().ToString() });
                            }
                        }
                        else
                        {
                            MessageBox.Show("You must enter software license keys");
                            return false;
                        }
                    }
                    break;
                case "General Mills Developed":
                    break;
                default:
                    MessageBox.Show("Invalid Software Origin");
                    return false;
            }

            licData.DivisionOfOwnership = ((Division)boxDivisonOfOwnership.SelectedItem).Name.ToString();

            if (panelDepartmentOfOwnership.Visibility == System.Windows.Visibility.Visible)
            {
                licData.DepartmentOfOwnership = ((Department)boxDepartmentOfOwnership.SelectedItem).name.ToString();
            }

            return true;
        }
        private void btnSaveLicensingData_Click(object sender, RoutedEventArgs e)
        {
            if (validateInputFields())
            {
                busyIndicatorMain.IsBusy = true;
                busyIndicatorMain.BusyContent = "Saving Licensing Data";

                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.saveLicensingDataCompleted += new EventHandler<saveLicensingDataCompletedEventArgs>(proxy_saveLicensingDataCompleted);
                proxy.saveLicensingDataAsync(licData);
            }
        }

        void proxy_saveLicensingDataCompleted(object sender, saveLicensingDataCompletedEventArgs e)
        {
            currentRequest.LicensingStepComplete = DateTime.UtcNow;

            App.Current.Resources.Remove("Current Request");
            App.Current.Resources.Add("Current Request", currentRequest);

            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.saveRequestCompleted += new EventHandler<saveRequestCompletedEventArgs>(proxy_saveRequestCompleted);
            proxy.saveRequestAsync(currentRequest);
        }

        void proxy_saveRequestCompleted(object sender, saveRequestCompletedEventArgs e)
        {
            panelLicenseEdit.Visibility = System.Windows.Visibility.Visible;
            lockInputs();
            busyIndicatorMain.IsBusy = false;
        }

        private void btnRejectRequest_Click(object sender, RoutedEventArgs e)
        {
            Web.User user = WebContext.Current.User;

            currentRequest.Status = "Rejected";
            currentRequest.LicensingOwner = user.DisplayName.ToString();

            App.Current.Resources.Remove("Current Request");
            App.Current.Resources.Add("Current Request", currentRequest);

            busyIndicatorMain.IsBusy = true;
            busyIndicatorMain.BusyContent = "Rejecting Request";

            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.saveRequestAsync(currentRequest);
            proxy.getRequestCompleted += new EventHandler<getRequestCompletedEventArgs>(proxy_getRequestCompleted_Rejected);
            proxy.getRequestAsync(currentRequest.requestID, 5);
        }

        void proxy_getRequestCompleted_Rejected(object sender, getRequestCompletedEventArgs e)
        {
            if (e.Result.Stage.Equals("Licensing"))
            {
                busyIndicatorMain.BusyContent = e.Result.Status.ToString();
                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.getRequestCompleted += new EventHandler<getRequestCompletedEventArgs>(proxy_getRequestCompleted_Rejected);
                proxy.getRequestAsync(currentRequest.requestID, 5);
            }
            else
            {
                busyIndicatorMain.IsBusy = false;
                this.NavigationService.Navigate(new Uri("/Home", UriKind.Relative));
            }
        }

        void proxy_saveRequestCompleted_Reject(object sender, saveRequestCompletedEventArgs e)
        {
            panelLicenseEdit.Visibility = System.Windows.Visibility.Visible;
            lockInputs();
            busyIndicatorMain.IsBusy = false;
        }

        private void boxGroupName_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
                _errorCount++;
            else if (e.Action == ValidationErrorEventAction.Removed)
                _errorCount--;
        }

        private void boxADGroupNotes_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
                _errorCount++;
            else if (e.Action == ValidationErrorEventAction.Removed)
                _errorCount--;
        }

        private void boxADGroupDescription_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
                _errorCount++;
            else if (e.Action == ValidationErrorEventAction.Removed)
                _errorCount--;
        }

        private void boxADGroupOwner_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
                _errorCount++;
            else if (e.Action == ValidationErrorEventAction.Removed)
                _errorCount--;
        }

        private void btnPendingRequest_Click(object sender, RoutedEventArgs e)
        {
            Web.User user = WebContext.Current.User;

            currentRequest.LicensingOwner = user.DisplayName.ToString().Split('\\')[1];
            currentRequest.Status = "Pending";
            App.Current.Resources.Remove("Current Request");
            App.Current.Resources.Add("Current Request", currentRequest);

            busyIndicatorMain.IsBusy = true;
            busyIndicatorMain.BusyContent = "Placing request in Pending State";

            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.saveRequestAsync(currentRequest);
            proxy.saveRequestCompleted += new EventHandler<saveRequestCompletedEventArgs>(proxy_saveRequestCompleted_Pending);
        }

        void proxy_saveRequestCompleted_Pending(object sender, saveRequestCompletedEventArgs e)
        {
            busyIndicatorMain.IsBusy = false;
        }

        private void btnAddWorklogEntry_Click(object sender, RoutedEventArgs e)
        {
            Web.User user = WebContext.Current.User;

            GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
            proxy.getUserFriendlyNameCompleted += new EventHandler<getUserFriendlyNameCompletedEventArgs>(proxy_getUserFriendlyNameCompleted_AddWorkLogEntry);
            proxy.getUserFriendlyNameAsync(user.Name.Split('\\')[1].ToString(), user.Name.Split('\\')[0].ToString());
            busyIndicatorMain.BusyContent = "Creating New Work Log Entry";
            busyIndicatorMain.IsBusy = true;
        }

        void proxy_getUserFriendlyNameCompleted_AddWorkLogEntry(object sender, getUserFriendlyNameCompletedEventArgs e)
        {
            busyIndicatorMain.IsBusy = false;
            WorkLogEntry entry = new WorkLogEntry()
            {
                Note = String.Empty,
                NoteDate = DateTime.UtcNow,
                RequestID = currentRequest.requestID,
                UserName = e.Result.ToString(),
                WorkLogID = System.Guid.NewGuid().ToString()
            };

            WorkLogEntryDetails childWindow = new WorkLogEntryDetails(entry);
            childWindow.Closed += new EventHandler(childWindow_Closed_WorkLogEntry);

            childWindow.Show();
        }

        void childWindow_Closed_WorkLogEntry(object sender, EventArgs e)
        {
            WorkLogEntryDetails childWindow = (WorkLogEntryDetails)sender;
            if (childWindow.DialogResult.Value == true)
            {
                busyIndicatorMain.IsBusy = true;
                busyIndicatorMain.BusyContent = "Saving Work Log Entry";
                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.createWorkLogEntryCompleted += new EventHandler<createWorkLogEntryCompletedEventArgs>(proxy_createWorkLogEntryCompleted);
                proxy.createWorkLogEntryAsync(childWindow.entry.UserName, childWindow.entry.RequestID, childWindow.entry.Note, childWindow.entry.NoteDate);
            }
        }

        void proxy_createWorkLogEntryCompleted(object sender, createWorkLogEntryCompletedEventArgs e)
        {
            busyIndicatorMain.IsBusy = false;
            WorkLogEntry modifiedWorkLogEntry = e.Result;
            modifiedWorkLogEntry.NoteDate = modifiedWorkLogEntry.NoteDate.ToLocalTime();
            workLog.Add(modifiedWorkLogEntry);
        }

        private void gridWorkLog_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            WorkLogEntry entry = (WorkLogEntry)gridWorkLog.SelectedItem;
            if (entry != null)
            {
                WorkLogEntryDetails childWindow = new WorkLogEntryDetails(entry);
                childWindow.boxWorkLogNotes.IsReadOnly = true;
                childWindow.Show();
            }
        }

        void proxy_getUserFriendlyNameCompleted_validateUser(object sender, getUserFriendlyNameCompletedEventArgs e)
        {
            busyIndicatorMain.IsBusy = false;
            if (e.Result.ToString().Equals(String.Empty))
            {
                MessageBox.Show("Invalid User");
            }
            else
            {
                MessageBox.Show("Found User: " + e.Result.ToString());
            }
        }

        private void boxADGroupDestinationOU_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            currentRequest.DestinationOU = boxADGroupDestinationOU.SelectedItem.ToString();
            App.Current.Resources.Remove("Current Request");
            App.Current.Resources.Add("Current Request", currentRequest);
        }
        void proxy_getGroupFriendlyNameCompleted_GroupNameChange(object sender, getGroupFriendlyNameCompletedEventArgs e)
        {
            spinnerGroupName.Visibility = System.Windows.Visibility.Collapsed;
            if (!(e.Result.Equals(String.Empty)))
            {
                SolidColorBrush greenBrush = new SolidColorBrush();
                greenBrush.Color = Colors.Green;

                boxADGroupNameNeworExisting.Text = "Existing Group";
                boxADGroupNameNeworExisting.Foreground = greenBrush;
                boxADGroupNameNeworExisting.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                SolidColorBrush blueBrush = new SolidColorBrush();
                blueBrush.Color = Colors.Blue;

                boxADGroupNameNeworExisting.Text = "New Group";
                boxADGroupNameNeworExisting.Foreground = blueBrush;
                boxADGroupNameNeworExisting.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void boxADGroupName_TextChanged(object sender, TextChangedEventArgs e)
        {           
            boxADGroupNameNeworExisting.Visibility = System.Windows.Visibility.Collapsed;
            spinnerGroupName.Visibility = System.Windows.Visibility.Visible;

            if (!boxADGroupName.Text.Equals(String.Empty))
            {
                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.getGroupFriendlyNameCompleted += new EventHandler<getGroupFriendlyNameCompletedEventArgs>(proxy_getGroupFriendlyNameCompleted_GroupNameChange);
                proxy.getGroupFriendlyNameAsync(boxADGroupName.Text, "genmills.com");
            }
        }

        private void boxADGroupOwner_TextChanged(object sender, TextChangedEventArgs e)
        {
            boxADGroupOwnerValid.Visibility = System.Windows.Visibility.Collapsed;
            spinnerGroupOwner.Visibility = System.Windows.Visibility.Visible;

            if (!(boxADGroupOwner.Text.Equals(String.Empty)))
            {
                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();
                proxy.getUserFriendlyNameCompleted += new EventHandler<getUserFriendlyNameCompletedEventArgs>(proxy_getUserFriendlyNameCompleted_OwnerTextChange);
                proxy.getUserFriendlyNameAsync(boxADGroupOwner.Text, "genmills.com");
            }
        }

        void proxy_getUserFriendlyNameCompleted_OwnerTextChange(object sender, getUserFriendlyNameCompletedEventArgs e)
        {
            try
            {
                spinnerGroupOwner.Visibility = System.Windows.Visibility.Collapsed;
                if (!(e.Result.Equals(String.Empty)))
                {
                    SolidColorBrush greenBrush = new SolidColorBrush();
                    greenBrush.Color = Colors.Green;

                    boxADGroupOwnerValid.Text = "Valid User";
                    boxADGroupOwnerValid.Foreground = greenBrush;
                    boxADGroupOwnerValid.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    SolidColorBrush redBrush = new SolidColorBrush();
                    redBrush.Color = Colors.Red;

                    boxADGroupOwnerValid.Text = "Invalid User";
                    boxADGroupOwnerValid.Foreground = redBrush;
                    boxADGroupOwnerValid.Visibility = System.Windows.Visibility.Visible;
                }
            }
            catch
            {
                SolidColorBrush redBrush = new SolidColorBrush();
                redBrush.Color = Colors.Red;

                boxADGroupOwnerValid.Text = "Invalid User";
                boxADGroupOwnerValid.Foreground = redBrush;
                boxADGroupOwnerValid.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void btnSelectAllPreviousVersion_Click(object sender, RoutedEventArgs e)
        {
            foreach (ApplicationInformation userInfo in PreviousVersionSoftwareUsers)
            {
                userInfo.include = true;
            }
        }

        private void btnSelectAllCurrentVersionRemoved_Click(object sender, RoutedEventArgs e)
        {
            foreach (ApplicationInformation userInfo in RemovedUsersCurrVersion)
            {
                userInfo.include = true;
            }
        }

        private void btnSelectAllCurrentVersion_Click(object sender, RoutedEventArgs e)
        {
            foreach (ApplicationInformation userInfo in SoftwareUsers)
            {
                userInfo.include = true;
            }
        }

        private void btnUnSelectAllCurrentVersionRemoved_Click(object sender, RoutedEventArgs e)
        {

            foreach (ApplicationInformation userInfo in RemovedUsersCurrVersion)
            {
                userInfo.include = false;
            }
        }

        private void btnUnSelectAllPreviousVersion_Click(object sender, RoutedEventArgs e)
        {
            foreach (ApplicationInformation userInfo in PreviousVersionSoftwareUsers)
            {
                userInfo.include = false;
            }
        }

        private void btnUnSelectAllCurrentVersion_Click(object sender, RoutedEventArgs e)
        {
            foreach (ApplicationInformation userInfo in SoftwareUsers)
            {
                userInfo.include = false;
            }
        }

        private void boxRequestSource_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (boxRequestSource != null)
            {
                currentRequest.IncomingSource = ((ComboBoxItem)boxRequestSource.SelectedItem).Content.ToString();

                App.Current.Resources.Remove("Current Request");
                App.Current.Resources.Add("Current Request", currentRequest);
            }
        }

        private void btnSaveChanges_Click(object sender, RoutedEventArgs e)
        {
            if (_errorCount == 0 && boxADGroupOwnerValid.Text.Equals("Valid User"))
            {
                currentRequest.LicensingOwner = boxADGroupOwner.Text.ToString();
                currentRequest.ADGroupDescription = boxADGroupDescription.Text.ToString();
                currentRequest.ADGroupName = boxADGroupName.Text.ToString();
                currentRequest.ADGroupNotes = boxADGroupNotes.Text.ToString();
                currentRequest.DestinationOU = boxADGroupDestinationOU.SelectedItem.ToString();

                App.Current.Resources.Remove("Current Request");
                App.Current.Resources.Add("Current Request", currentRequest);

                GranitePackagingServiceSoapClient proxy = new GranitePackagingServiceSoapClient();

                proxy.saveRequestCompleted += new EventHandler<saveRequestCompletedEventArgs>(proxy_saveRequestCompleted_SaveChanges);
                proxy.saveRequestAsync(currentRequest);
                busyIndicatorMain.IsBusy = true;
                busyIndicatorMain.BusyContent = "Saving Request";
            }
            else
            {
                MessageBox.Show("Invalid Entry");
            }
        }

        void proxy_saveRequestCompleted_SaveChanges(object sender, saveRequestCompletedEventArgs e)
        {
            busyIndicatorMain.IsBusy = false;
        }
    }
}
